<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/8/21
 * Time: 16:04
 */

namespace app\back\controller;
use app\back\validate\ArticleNew;
use app\common\model\Article as ArticleModel;
use app\common\model\Category as CategoryModel;
use app\common\model\Tag as TagModel;
use think\Request;
use think\Session;

class Article extends BaseController
{
    /**
     * 文章列表页
     * @return \think\response\View
     */
    public function index()
    {
        $articles = ArticleModel::field('id,title,image_id,status,read_count,user_id,updated_at')
            ->with(['comments', 'image'])
            ->where([])
            ->order('updated_at desc')
            ->paginate(10)
        ;
        $page = $articles->render();
        $this->assign(compact('articles', 'page'));
        return view();
    }

    /**
     * 文章添加页
     * @return \think\response\View
     */
    public function add()
    {
        $category_model = new CategoryModel();
        $categories = $category_model->getTreeData('tree', 'sort_number');
        $tags = TagModel::all();
        $this->assign(compact('categories', 'tags'));
        return view();
    }

    /**
     * 文章添加处理
     * @param Request $request
     * @return \think\response\Json
     */
    public function addProcess(Request $request)
    {
        (new ArticleNew())->goCheck();
        if ($request->isPost()) {
            $user_id = Session::get('login.id');
            $data = $request->request();
            $model = new ArticleModel();
            $model->title            = $data['title'];              // 标题
            $model->keywords         = $data['keywords'];           // 关键词
            $model->summary          = $data['summary'];            // 简介
            $model->content          = $data['content'];            // 文章内容 MD
            $model->html_content     = $data['html_content'];       // 文章内容 HTML
            $model->meta_title       = $data['meta_title'];         // SEO标题
            $model->meta_keywords    = $data['meta_keywords'];      // SEO关键词
            $model->meta_description = $data['meta_description'];   // SEO描述
            $model->status           = $data['status'];             // 状态
            $model->user_id          = $user_id;
            //dump($request->request());
            // tag[new]不为空时，在标签表增加新的标签，并与文章关联

            $model->save();
            if ($model->id) {
                // 添加文章分类表的关联
                $model->categories()->save([
                    'article_id'    =>  $model->id,
                    'category_id'   =>  $request->post('category_id'),
                ]);

                // 添加标签表的关联
                if ($data['tag']['new'] != '') {
                    $tag_new_arr = explode(',', $data['tag']['new']);
                    foreach ($tag_new_arr as $tag_name)
                    {
                        // 在数据库中没有同名的标签，才可以新增
                        $tag_model = new TagModel();
                        if (!$tag_model->checkTagName($tag_name)) {
                            $tag_model->save([
                                'user_id'   =>$user_id,
                                'name'      =>$tag_name
                            ]);
                            // 添加成功的标签，与文章关联
                            if ($tag_model->id) {
                                $model->tags()->save([
                                    'article_id'    =>  $model->id,
                                    'tag_id'        =>  $tag_model->id,
                                ]);
                            }
                        }
                    }
                }
                unset($data['tag']['new']);
                foreach ($data['tag'] as $tag_id)
                {
                    $model->tags()->save([
                        'article_id'    =>  $model->id,
                        'tag_id'        =>  $tag_id,
                    ]);
                }
                return json(['status' => 'success', 'code'  =>  '00000', 'result' => ['id' => $model->id]]);
            }
            return json(['status' => 'failed', 'code'  =>  '10000'], 400);
        }
        return json(['status' => 'failed', 'code'  =>  '10008'], 400);
    }

    /**
     * 上传markdown图片
     * @return \think\response\Json
     */
    public function markdownImage()
    {
        $file = request()->file('editormd-image-file');
        if (!$file) return json(['status'=>'failed', 'code'=>'10006'], 400);
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'markdown_cover');
        if ($info) {
            $base_dir = ROOT_PATH . 'public' . DS;
            $image = \think\Image::open($base_dir . 'markdown_cover' . DS . $info->getSaveName());
            $thumb_name = 'thumb_' . date("Y-m-d_") . $info->getFilename();
            $image->thumb(config('image_max_width'), config('image_max_height'), \think\Image::THUMB_SCALING)
                ->save($base_dir . 'markdown' . DS . $thumb_name);
            $url = '/markdown/' . $thumb_name;
            return json(['success'=>1, 'url'=>$url]);
        }else{
            // 上传失败获取错误信息->filename
            echo $file->getError();
        }
    }

    /**
     * 文章编辑页面
     * @param $id
     * @return \think\response\View
     */
    public function edit($id)
    {
        $category_model = new CategoryModel();
        $categories = $category_model->getTreeData('tree', 'sort_number');
        $tags = TagModel::all();
        $article = ArticleModel::with(['user', 'categories.category', 'tags.tag'])->find($id);
        return view('edit', compact('categories', 'tags', 'article', 'data'));
    }

    /**
     * 文章编辑处理
     * @param Request $request
     * @return \think\response\Json
     */
    public function editProcess(Request $request)
    {
        (new ArticleNew())->goCheck();
        if ($request->isPost()) {
            $model = ArticleModel::find($request->post('id'));
            $data = $request->request();
            $model->title            = $data['title'];                   // 标题
            $model->keywords         = $data['keywords'];                // 关键词
            $model->summary          = $data['summary'];                 // 简介
            $model->content          = $data['content'];                 // 文章内容 MD
            $model->html_content     = $data['html_content'];            // 文章内容 HTML
            $model->meta_title       = $data['meta_title'];              // SEO标题
            $model->meta_keywords    = $data['meta_keywords'];           // SEO关键词
            $model->meta_description = $data['meta_description'];        // SEO描述
            $model->status           = $data['status'];                  // 状态
            $model->user_id          = Session::get('login.id');;

            $model->save();
            if ($model->id) {
                // 先删除旧的文章分类表关联，再添加文章分类表的关联
                $model->categories()->where(['article_id'=>$model->id])->delete();
                $model->categories()->save([
                    'article_id'    =>  $model->id,
                    'category_id'   =>  $data['category_id'],
                ]);
                // 添加标签表的关联
                $tag_new_str = $data['tag']['new'];
                unset($data['tag']['new']);
                $model->tags()->where(['article_id'=>$model->id])->delete();
                foreach ($data['tag'] as $tag_id)
                {
                    $model->tags()->save([
                        'article_id'    =>  $model->id,
                        'tag_id'        =>  $tag_id,
                    ]);
                }
                if ($tag_new_str != '') {
                    $tag_new_arr = explode(',', $tag_new_str);
                    foreach ($tag_new_arr as $tag_name)
                    {
                        // 在数据库中没有同名的标签，才可以新增
                        $tag_model = new TagModel();
                        if (!$tag_model->checkTagName($tag_name)) {
                            $tag_model->save([
                                'user_id'   =>Session::get('login.id'),
                                'name'      =>$tag_name
                            ]);
                            // 添加成功的标签，与文章关联
                            if ($tag_model->id) {
                                $model->tags()->save([
                                    'article_id'    =>  $model->id,
                                    'tag_id'        =>  $tag_model->id,
                                ]);
                            }
                        }
                    }
                }
                return json(['status' => 'success', 'code'  =>  '00000', 'result' => ['id' => $model->id]]);
            }
            return json(['status' => 'failed', 'code'  =>  '10000'], 400);
        }
        return json(['status' => 'failed', 'code'  =>  '10008'], 400);
    }

    /**
     * 文章软删除
     * @param Request $request
     * @return \think\response\Json
     */
    public function delete(Request $request)
    {
        if ($request->post('id')) {
            ArticleModel::destroy($request->post('id'));
            return json(['status' => 'success', 'code'  =>  '00000', 'result' => ['id' => $request->post('id')]]);
        }
        return json(['status' => 'failed', 'code'  =>  '10008'], 400);
    }

    /**
     * 修改图片状态
     * @param Request $request
     * @return \think\response\Json
     */
    public function changeStatus(Request $request)
    {
        if ($request->post('id')) {
            $model = ArticleModel::find($request->post('id'));
            $model->status = $request->post('status');
            $model->user_id = Session::get('login.id');;
            $model->save();
            if ($model->id) {
                return json(['status' => 'success', 'code'  =>  '00000', 'result' => ['id' => $model->id]]);
            }
            return json(['status' => 'failed', 'code'  =>  '10000'], 400);
        }
        return json(['status' => 'failed', 'code'  =>  '10008'], 400);
    }

    /**
     * 关联图片
     * @param Request $request
     * @return \think\response\Json
     */
    public function changeImage(Request $request)
    {
        $tid = $request->post('tid');
        $id = $request->post('id');
        if ($tid && $id) {
            $model = ArticleModel::find($tid);
            $model->image_id = $id;
            $model->save();
            if ($model->id) {
                return json(['status' => 'success', 'code'  =>  '00000']);
            }
            return json(['status' => 'failed', 'code'  =>  '10000'], 400);
        }
        return json(['status' => 'failed', 'code'  =>  '10005'], 400);
    }

}